//!@author denglibin
//!@date 2025/6/10 9:25
//!@desc 动态数据导入

use crate::app;
use crate::sys::global::{GlobalError, GlobalResult};
use my_util_lib::excel_util;
use crate::dao::mysql::dong_tai_dao;
use crate::entity::dong_tai::{DongTai, DongTai2};

//第一个表
pub async fn import_from_excel(excel_path: &str) -> GlobalResult<()> {
    let app_state = app::init().await?;
    let path = excel_path.to_string();
    //读取excel数据
    let mut excel_model = tokio::task::spawn_blocking(move || {
        let r = excel_util::read_xlsx(&path);
        match r {
            Ok(model) => Ok(model),
            Err(e) => Err(GlobalError::new(e.to_string())),
        }
    })
    .await??;
    //转实例对象
    let mut datas: Vec<DongTai> = Vec::new();
    let mut id = 1;
    for  sheet in excel_model.sheets.iter_mut() {
        sheet.rows.remove(0); //第一行不要
        for row in sheet.rows.iter() {
            let mut dong_tai = row_to_obj(row);
            dong_tai.id = id;
            id +=1;
            datas.push(dong_tai);
        }
    }
    //添加到数据库
    dong_tai_dao::insert_batch(&app_state.pool, &datas).await

}


//第二个表
pub async fn import_from_excel2(excel_path: &str) -> GlobalResult<()> {
    let app_state = app::init().await?;
    let path = excel_path.to_string();
    //读取excel数据
    let mut excel_model = tokio::task::spawn_blocking(move || {
        let r = excel_util::read_xlsx(&path);
        match r {
            Ok(model) => Ok(model),
            Err(e) => Err(GlobalError::new(e.to_string())),
        }
    })
        .await??;
    //转实例对象
    let mut datas: Vec<DongTai2> = Vec::new();
    let mut id = 1;
    for  sheet in excel_model.sheets.iter_mut() {
        sheet.rows.remove(0); //第一行不要
        for row in sheet.rows.iter() {
            let mut dong_tai = row_to_obj2(row);
            dong_tai.id = id;
            id +=1;
            datas.push(dong_tai);
        }
    }
    //添加到数据库
    dong_tai_dao::insert_batch2(&app_state.pool, &datas).await

}

fn row_to_obj(row: &Vec<String>) -> DongTai {
    let mut dong_tai = DongTai {
        id: 0,
        title: row[0].to_string(),
        author:  row[1].to_string(),
        lei_xing: row[3].to_string(),
        source_web: row[5].to_string(),
        pub_time: row[6].to_string(),
        file_path: row[2].to_string(),
    };
    dong_tai.file_path = dong_tai.file_path.replace("\\", "/").replace("/资源导出/动态/", "");

    dong_tai
}
//第二个
fn row_to_obj2(row: &Vec<String>) -> DongTai2 {
    let mut dong_tai = DongTai2 {
        id: 0,
        title: row[0].to_string(),
        author:  row[1].to_string(),
        lei_xing: row[2].to_string(),
        source_web: row[6].to_string(),
        pub_time: row[4].to_string(),
        file_path: row[5].to_string(),
    };
    dong_tai.file_path = dong_tai.file_path.replace("\\", "/").replace("/资源导出/动态/", "");

    dong_tai
}
